package com.xiaoyg.algorithm;

import java.util.HashMap;
import java.util.Map;

public class twoSum {

    public static void main(String[] args) {
        System.out.printf("两数之和=》"+ solution1(new int[]{1, 2, 3, 4, 5, 6}, 5));
    }


    //暴力穷举算法
    public static int[] solution1(int [] nums, int target){
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[i]+nums[j] == target){
                    System.out.println(i+":"+j);
                    return new int[]{i,j};
                }
            }
        }
        return new int [0];
    }




    public static int[] solution(int [] nums, int target){
        //建立一个备忘录，已经遍历过的数据，存储起来
        Map<Integer,Integer> map = new HashMap<Integer,Integer>();
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(target - nums[i])){
                System.out.println(map.get(target - nums[i])+":"+i);
                return new int [] {map.get(target - nums[i]),i};
            }
            map.put(nums[i],i);
        }
        return new int [0];
    }

}
